package com.example.treehole.fragmnet;


import android.graphics.Color;
import android.view.View;
import android.view.animation.Animation;

import androidx.annotation.NonNull;

import com.example.treehole.R;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.AnalyseResponse;
import com.example.treehole.utils.DateUtils;
import com.example.treehole.widget.TextRoundProgress;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;

public class fragment2 extends BaseFragment {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.trp_score)
    TextRoundProgress trpScore;
    @BindView(R.id.lc_score)
    LineChart lcScore;
    @BindView(R.id.pc_score)
    PieChart pcScore;

    public static fragment2 newInstance() {
        return new fragment2();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragmen2;
    }


    @Override
    protected void initData(View view) {
        loadData();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
    }

    private void loadData() {
        String id=getStringFromSp("id");
        String url = ApiConfig.GET_EMOTION_DATA + "/" + id;
        Api.config(url, new HashMap<>()).getRequest(requireContext(), new Callback() {
            @Override
            public void onSuccess(String res) {
                refreshLayout.finishRefresh(true);
                try {
                    AnalyseResponse analyseResponse = new Gson().fromJson(res, AnalyseResponse.class);
                    String code = analyseResponse.getCode();
                    if (code.equals("200")) {
                        AnalyseResponse.DataDTO dataDTO = analyseResponse.getData();
                        trpScore.setProgress(dataDTO.getMark());
                        trpScore.setText(dataDTO.getMark()+"");
                        lineChartInit(dataDTO.getLineChartData());
                        pieChartInit(dataDTO.getPieChartData());
                    } else {
                        showToastSync(analyseResponse.getMsg());
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    showNoData();
                }
            }
            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                showToastSync(getString(R.string.check_network));
                showNoData();
            }
        });
    }

    private void showNoData() {
        //设置无数据显示
        lcScore.setNoDataText(getString(R.string.load_error));
        lcScore.invalidate();
        pcScore.setNoDataText(getString(R.string.load_error));
        pcScore.invalidate();
    }

    private void lineChartInit(Map<Integer, Float> lineChartData) {
        //设置点的数据
        List<Entry> entries = new ArrayList<>();
        for (int i = 6; i >=0; i--) {
            Float mark=lineChartData.get(i);
            if (mark!=null)
                entries.add(new Entry(6-i, mark));
            else
                entries.add(new Entry(6-i,0));
        }
        //准备好每个点对应的x轴数值
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            list.add(DateUtils.getPastDate(6-i));
        }
        XAxis xAxis = lcScore.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(list));
        //设置x轴样式
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        lcScore.getDescription().setEnabled(false);
        lcScore.getAxisRight().setEnabled(false);
        //设置图例样式
        Legend legend = lcScore.getLegend();
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setXOffset(-15f);
        legend.setYOffset(5f);
        legend.setTextSize(10);
        //显示
        LineDataSet dataSet = new LineDataSet(entries, "本周心情指数");
        dataSet.setColor(getContext().getResources().getColor(R.color.blue));
        dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        LineData lineData = new LineData(dataSet);
        lcScore.setData(lineData);
        lcScore.invalidate();
    }


    private void pieChartInit(Map<Integer, Float> pieChartData) {
        //设置暂时的文字信息
        String[] str= {getString(R.string.category_one),
                getString(R.string.category_two),
                getString(R.string.category_three),
                getString(R.string.category_four)};
        //设置数据
        List<PieEntry> entries = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Float percent=pieChartData.get(4-i);
            if (percent!=null)
                entries.add(new PieEntry(percent,str[i]));
            else
                entries.add(new PieEntry(0,str[i]));
        }
        //颜色
        int[] colors = {
                getResources().getColor(R.color.scoreFourTime),
                getResources().getColor(R.color.scoreThreeTime),
                getResources().getColor(R.color.scoreTwoTime),
                getResources().getColor(R.color.scoreOneTime),
        };
        //设置相关属性
        pcScore.setUsePercentValues(true);//设置使用百分比（后续有详细介绍）
        pcScore.getDescription().setEnabled(false);//设置描述
        pcScore.setExtraOffsets(10, 5, 10, 10); //设置边距
        pcScore.setDragDecelerationFrictionCoef(0.95f);//设置摩擦系数（值越小摩擦系数越大）
        pcScore.setCenterText("");//设置环中的文字
        pcScore.setRotationEnabled(true);//是否可以旋转
        pcScore.setHighlightPerTapEnabled(true);//点击是否放大
        pcScore.setCenterTextSize(22f);//设置环中文字的大小
        pcScore.setDrawCenterText(true);//设置绘制环中文字
        pcScore.setRotationAngle(120f);//设置旋转角度
        pcScore.setTransparentCircleRadius(61f);//设置半透明圆环的半径,看着就有一种立体的感觉
        pcScore.setDrawHoleEnabled(false);//这个方法为true就是环形图，为false就是饼图
        pcScore.setHoleColor(Color.WHITE);//设置环形中间空白颜色是白色
        pcScore.setTransparentCircleColor(Color.WHITE);//设置半透明圆环的颜色
        pcScore.setTransparentCircleAlpha(110);//设置半透明圆环的透明度
        //图例设置
        Legend legend = pcScore.getLegend();
        legend.setEnabled(true);//是否显示图例
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);//图例相对于图表横向的位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);//图例相对于图表纵向的位置
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);//图例显示的方向
        legend.setTextSize(10f);
        legend.setDrawInside(false);
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        //显示
        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setSliceSpace(5f);//设置饼块之间的间隔
        dataSet.setSelectionShift(5f);//设置饼块选中时偏离饼图中心的距离
        dataSet.setColors(colors);//设置饼块的颜色
        dataSet.setValueLinePart1OffsetPercentage(70f);//数据连接线距图形片内部边界的距离，为百分数
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.8f);
        dataSet.setValueLineColor(Color.YELLOW);//设置连接线的颜色
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        PieData pieData = new PieData(dataSet);
        pieData.setValueFormatter(new PercentFormatter());
        pieData.setValueTextSize(11f);
        pieData.setValueTextColor(Color.DKGRAY);
        pcScore.setData(pieData);
        pcScore.highlightValues(null);
        pcScore.invalidate();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter)
            loadData();
        return super.onCreateAnimation(transit, enter, nextAnim);
    }
}